package cn.usian.jyzx.cart.service.impl;

import cn.usian.jyzx.cart.fegin.ProductFegin;
import cn.usian.jyzx.cart.service.CartService;
import cn.usian.jyzx.common.util.UserInfoThreadLocalUtil;
import cn.usian.jyzx.model.constant.Constant;
import cn.usian.jyzx.model.entity.product.ProductSku;
import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import cn.usian.jyzx.model.vo.h5.CartInfo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 11 06 14 03
 **/
@Service
@Slf4j
public class CartServiceImpl  implements CartService {

    @Autowired RedisTemplate redisTemplate;

    @Autowired ProductFegin productFegin;

    public UserInfo getCurrentUserInfo(String token) {
        log.info("getCurrentUserInfo token:{}",token);
        String userInfoStr = (String)redisTemplate.opsForValue().get(Constant.LOGIN_TOKEN_KEY+token) ;
        log.info("userInfoStr:{}",userInfoStr);

        //json 字符串转成 UserInfo对象
        UserInfo userInfo = com.alibaba.fastjson2.JSON.parseObject(userInfoStr,UserInfo.class);


        return userInfo;
    }
    @Override
    public void addCart(Long skuId, Integer num,String token) {

//        ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
//        String userStr = stringThreadLocal.get();
//        log.info("从ThreadLocal获取userStr：{}",userStr);
//
//
//        log.info("addCart添加购物车：skuId：{},num:{}",skuId,num);
//        UserInfo userInfo = UserInfoThreadLocalUtil.getUserInfo();
//
//        log.info("从UserInfoThreadLocalUtil获取UserInfo：{}", JSON.toJSONString(userInfo));
        UserInfo userInfo = getCurrentUserInfo(token);

        log.info("UserInfo：{}", JSON.toJSONString(userInfo));
        Long id = userInfo.getId();

         //KEY:Constant.CART_LIST_KEY + id
         //key:skuId
         // value:json String
        ProductSku productSku = productFegin.findById(skuId);
        log.info("通过fegin远程调用结果，productSku:{}",productSku.toString());

        String cartJsonStr = (String)redisTemplate.opsForHash().get(Constant.CART_LIST_KEY + id, skuId);
        if(StringUtils.isEmpty(cartJsonStr)){
            log.info("购物车中没有该商品，添加购物车");
            CartInfo cartInfo = new CartInfo();
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuNum(num);
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);

            String cartInfoStr = JSON.toJSONString(cartInfo);
            redisTemplate.opsForHash().put(Constant.CART_LIST_KEY + id,skuId,cartInfoStr);




        }else{
            log.info("购物车中有该商品，更新购物车");
            CartInfo cartInfo = JSON.parseObject(cartJsonStr, CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum()+num);
            String cartInfoStr = JSON.toJSONString(cartInfo);
            redisTemplate.opsForHash().put(Constant.CART_LIST_KEY + id,skuId,cartInfoStr);
        }



    }

    @Override
    public List<CartInfo> cartList(String token) {
        UserInfo userInfo = getCurrentUserInfo(token);

        log.info("UserInfo：{}", JSON.toJSONString(userInfo));
        Long id = userInfo.getId();

        // KEY:Constant.CART_LIST_KEY + id
        //从redis 里面通过userID 找到对应购物车数据
        List<Object> values = redisTemplate.opsForHash().values(Constant.CART_LIST_KEY + id);
        //
        //2024-11-07T09:05:15.118+08:00  INFO 64201 --- [nio-8084-exec-3] c.u.j.cart.service.impl.CartServiceImpl  : UserInfo：{"avatar":"http://139.198.127.41:9000/sph/20230505/default_handsome.jpg","createTime":1683854043000,"id":1,"isDeleted":0,"lastLoginIp":"127.0.0.1","lastLoginTime":1690250106000,"memo":"test","nickName":"test","password":"4297f44b13955235245b2497399d7a93","phone":"13700032456","sex":1,"status":1,"updateTime":1730762382000,"username":"13700032456"}
        //2024-11-07T09:05:15.120+08:00  INFO 64201 --- [nio-8084-exec-3] c.u.j.cart.service.impl.CartServiceImpl  : values:
        log.info("values:{}",values);
// values:[{"cartPrice":1999.00,"imgUrl":"https://img14.360buyimg.com/n1/s450x450_jfs/t1/240855/2/18613/161980/671f9217F0cd26bd6/3ff01504551ca51f.jpg","isChecked":1,"skuId":1,"skuName":"2309B 小米 红米Note10 5G手机 颜色:白色 内存:8G","skuNum":1}, {"cartPrice":2999.00,"imgUrl":"https://img14.360buyimg.com/n1/s450x450_jfs/t1/240855/2/18613/161980/671f9217F0cd26bd6/3ff01504551ca51f.jpg","isChecked":1,"skuId":2,"skuName":"2401B小米 红米Note10 5G手机 颜色:白色 内存:18G","skuNum":3}]

//        ArrayList<CartInfo> cartInfos = new ArrayList<>();
//
//
//        values.forEach(item->{
//          String i =   (String)item;
//            CartInfo cartInfo =  JSON.parseObject(i,CartInfo.class);
//            cartInfos.add(cartInfo);
//        });

        List<CartInfo> cartInfos =
                 values.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class))
                .collect(Collectors.toList());


        return cartInfos;
    }

    @Override
    public void deleteCart(Long skuId, String token) {
        UserInfo userInfo = getCurrentUserInfo(token);

        log.info("UserInfo：{}", JSON.toJSONString(userInfo));
        Long id = userInfo.getId();

        redisTemplate.opsForHash().delete(Constant.CART_LIST_KEY + id,skuId);

    }

    @Override
    public void checkCart(Long skuId, Integer isChecked, String token) {
        UserInfo userInfo = getCurrentUserInfo(token);

        log.info("UserInfo：{}", JSON.toJSONString(userInfo));
        Long id = userInfo.getId();

        //1--》0
        String cartJsonStr = (String)redisTemplate.opsForHash().get(Constant.CART_LIST_KEY + id, skuId);

        CartInfo cartInfo = JSON.parseObject(cartJsonStr, CartInfo.class);
        cartInfo.setIsChecked(isChecked);
        redisTemplate.opsForHash().put(Constant.CART_LIST_KEY + id,skuId,JSON.toJSONString(cartInfo));

    }

    @Override
    public void allCheckCart(Integer isChecked, String token) {
        UserInfo userInfo = getCurrentUserInfo(token);

        log.info("UserInfo：{}", JSON.toJSONString(userInfo));
        Long id = userInfo.getId();
        List<Object> values = redisTemplate.opsForHash().values(Constant.CART_LIST_KEY + id);

//        List<CartInfo> cartInfoStream = values.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class)).collect(Collectors.toList())
//        cartInfoStream.forEach(i->{
//            i.setIsChecked(isChecked);
//            redisTemplate.opsForHash().put(Constant.CART_LIST_KEY + id,i.getSkuId(),JSON.toJSONString(i));
//        });

        values.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class)).collect(Collectors.toList())
                .forEach(cartInfo -> {
                    cartInfo.setIsChecked(isChecked);
                    redisTemplate.opsForHash().put(Constant.CART_LIST_KEY + id, cartInfo.getSkuId(), JSON.toJSONString(cartInfo));
                });

    }

    @Override
    public void clearCart(String token) {
        UserInfo userInfo = getCurrentUserInfo(token);

        log.info("UserInfo：{}", JSON.toJSONString(userInfo));
        Long id = userInfo.getId();

        redisTemplate.delete(Constant.CART_LIST_KEY + id);
    }

    @Override
    public void deleteCheckedCart(String token) {


        log.info("deleteCheckedCart================");
        UserInfo userInfo = getCurrentUserInfo(token);

        log.info("UserInfo：{}", JSON.toJSONString(userInfo));
        Long id = userInfo.getId();

        //string --> cartInfo
        List<Object> values = redisTemplate.opsForHash().values(Constant.CART_LIST_KEY + id);

        //
        List<CartInfo> cartInfos =
                values.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class))
                        .collect(Collectors.toList());


        cartInfos.forEach(cartInfo -> {
            if(cartInfo.getIsChecked().intValue()==1){
                redisTemplate.opsForHash().delete(Constant.CART_LIST_KEY + id,cartInfo.getSkuId());
            }
        });

    }
}
